/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aptech.servlet;

import aptech.builder.XmlBuilder;
import aptech.container.Constants;
import aptech.data.ActivityBO;
import aptech.data.ScheduleActivityBO;
import aptech.data.TypeOfActivityBO;
import aptech.entities.Activity;
import aptech.entities.ScheduleActivity;
import aptech.entities.TypeOfActivity;
import aptech.entities.Users;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author home
 */
@WebServlet(name = "LoadDataServlet", urlPatterns = {"/LoadDataServlet"})
public class LoadDataServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String type = request.getParameter(Constants.TYPE);
            if (type.equals(Constants.GET_ACTIVITY_BY_SCHEDULE_ID)) {//danh sach activities theo scheduleid
                String id = request.getParameter(Constants.SCHEDULE_ACTIVITY_ID);
                if (id != null) {
                    List<Activity> list = new ActivityBO().getListByScheduleID(id);
                    String flag = list.get(0).getDateOfActivity();//gan = date dau tien
                    Map<String, List<Activity>> hashmap = new HashMap<String, List<Activity>>();
                    List<Activity> list_temp = new ArrayList<Activity>();
                    List<Activity> list_sub = null;
                    out.println("initial date: " + flag);
                    for (int i = 0; i < list.size(); i++) {
                        out.println("i = " + i + " - date: " + list.get(i).getDateOfActivity());
                        if (list.get(i).getDateOfActivity().equals(flag)) {
                            out.println("equal");
                            list_temp.add(list.get(i));
                            if (i == list.size() - 1) {
                                out.println("final");
                                list_sub = new ArrayList<Activity>();
                                list_sub = list_temp;
                                hashmap.put(flag, list_sub);
                                out.println("put");
                            }
                        } else {
                            out.println("not equal");
                            list_sub = new ArrayList<Activity>();
                            list_sub = list_temp;
                            hashmap.put(flag, list_sub);
                            out.println("put hashmap");
                            flag = list.get(i).getDateOfActivity();
                            out.println("flag date: " + flag);
                            list_temp = new ArrayList<Activity>();
                            list_temp.add(list.get(i));
                            if (i == list.size() - 1) {
                                out.println("final");
                                hashmap.put(flag, list_temp);
                                out.println("put hashmap");
                            }
                        }
                    }
                    out.println(XmlBuilder.getListActivitiesBySchedule(list));
                    //out.println("---------");
                    for (int i = 0; i < list.size(); i++) {
                        out.println(list.get(i).getDateOfActivity());
                    }
                    request.setAttribute("listactivity", hashmap);
                    request.getRequestDispatcher("activities.jsp").forward(request, response);
                }
            }
            //autoload ajax, su dung khi join activity ben index.jsp
            if(type.equals(Constants.GET_ACTIVITIES_BY_SCHEDULE_ID)){
                String id = request.getParameter(Constants.SCHEDULE_ACTIVITY_ID);
                //out.println("VAO DAY");
                List<Activity> list = (List<Activity>)new ActivityBO().getListByScheduleID(id);
                out.println(XmlBuilder.getListActivity_Mini(list));
                
            }
            if (type.equals(Constants.GET_SCHEDULES_COMING_SOON)) {
                List<ScheduleActivity> list = new ScheduleActivityBO().getScheduleActivityComingSoon();
                request.setAttribute(Constants.GET_SCHEDULES_COMING_SOON, list);
                //out.println(list.size());
            }
            if(type.equals(Constants.GET_SCHEDULES_ONGOING)){
                List<ScheduleActivity> list = new ScheduleActivityBO().getScheduleActivityOnGoing();
                request.setAttribute(Constants.GET_SCHEDULES_ONGOING, list);
            }
            if (type.equals(Constants.GET_ACTIVITY_BY_DAY_AND_SCHEDULE_ID)) {
                String id = request.getParameter(Constants.SCHEDULE_ACTIVITY_ID);
                String day = request.getParameter(Constants.ACTIVITY_DATE);
                if (id != null && day != null) {
                    List<Activity> list = new ActivityBO().getListByDayAndScheduleID(id, day);
                    if (list != null) {
                        out.println(XmlBuilder.getListActivitiesBySchedule(list));
                    } else {
                        out.println("<result>null</result>");
                    }

                }
            }
            if (type.equals(Constants.GET_TYPE_OF_ACTIVITY)) {
                List<TypeOfActivity> list = new TypeOfActivityBO().getAll();
                out.println(XmlBuilder.getListTypeOfActivity(list));
            }
            if (type.equals(Constants.GET_SESSION)) {
                HttpSession session = request.getSession();
                out.println("<result>" + XmlBuilder.getXMLUser((Users) session.getAttribute(Constants.LOGIN)) + "</result>");
            }
        } catch (Exception ex) {
            out.println("<result>error</result>");
            ex.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    //get list dates between from date to date.
    private List<Date> fetchdates(Date fechaInicial, Date fechaFinal) {
        List<Date> dates = new ArrayList<Date>();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(fechaInicial);

        while (calendar.getTime().before(fechaFinal)) {
            Date resultado = calendar.getTime();
            dates.add(resultado);
            calendar.add(Calendar.DATE, 1);
        }
        return dates;
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
